<template>
  <div class="layout">
    <el-form
      class="formDiv"
      ref="form"
      :model="requirement"
      :rules="requirementEditRules"
      label-width="200px">
    <ContainerTitle :text="isEdit ?'招聘需求编辑页' : '招聘需求申请页'" class="title"></ContainerTitle>
      <el-form-item label="标题：" prop="name">
        <el-input
          placeholder="请输入"
          :maxlength="20"
          v-model.trim="requirement.name"
          :disabled="isRequirementPass()">
        </el-input>
      </el-form-item>
      <el-form-item
        label="申请期限："
        style="text-align: left"
        prop="beginDate">
        <el-date-picker
          style="width: 291px"
          v-model.trim="requirement.beginDate"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="开始日期"
          :picker-options="startDateDisabled"
        ></el-date-picker>
        <span>~</span>
        <el-date-picker
          style="width: 291px"
          v-model.trim="requirement.endDate"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="结束日期"
          :picker-options="endDateDisabled"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="招聘岗位：" prop="post">
        <el-input
          placeholder="请输入"
          :maxlength="10"
          v-model.trim="requirement.post"
          :disabled="isRequirementPass()">
        </el-input>
      </el-form-item>
      <el-form-item label="岗位薪资：" prop="salary">
        <el-select
          placeholder="请选择"
          v-model.trim="requirement.salary"
          style="width: 100%">
          <el-option
            v-for="postSalaryOption in postSalaryOptions"
            :key="postSalaryOption.dictValue"
            :label="postSalaryOption.dictLabel"
            :value="postSalaryOption.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="招聘人数：" prop="amount">
        <el-input
          placeholder="请输入"
          :maxlength="3"
          v-model.trim="requirement.amount"
          >
        </el-input>
      </el-form-item>
      <el-form-item label="经验要求：" prop="experience">
        <el-select
          placeholder="请选择"
          v-model.trim="requirement.experience"
          style="width: 100%">
          <el-option
            v-for="experienceOption in experienceOptions"
            :key="experienceOption.dictValue"
            :label="experienceOption.dictLabel"
            :value="experienceOption.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学历要求：" prop="education">
        <el-select
          placeholder="请选择"
          v-model.trim="requirement.education"
          style="width: 100%">
          <el-option
            v-for="workerEducationOption in workerEducationOptions"
            :key="workerEducationOption.dictValue"
            :label="workerEducationOption.dictLabel"
            :value="workerEducationOption.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="工作类型：" prop="type">
        <el-select
          placeholder="请选择"
          v-model.trim="requirement.type"
          style="width: 100%">
          <el-option
            v-for="workerTypeOption in workerTypeOptions"
            :key="workerTypeOption.dictValue"
            :label="workerTypeOption.dictLabel"
            :value="workerTypeOption.dictValue"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="技能要求：" prop="postDesc">
        <el-input
          placeholder="请输入，例如：电气设计，图纸设计"
          type="textarea"
          resize="none"
          :maxlength="50"
          :autosize="{ minRows: 2, maxRows: 4 }"
          v-model="requirement.postDesc"
          :show-word-limit="true"></el-input>
      </el-form-item>
      <el-form-item label="工作地点：" prop="address">
        <el-input
          placeholder="请输入"
          :maxlength="50"
          v-model.trim="requirement.address"
          :disabled="isRequirementPass()">
        </el-input>
      </el-form-item>
      <el-form-item label="工作内容：" prop="responsibility">
        <el-input
          placeholder="请输入"
          type="textarea"
          resize="none"
          :maxlength="200"
          :autosize="{ minRows: 4, maxRows: 4 }"
          v-model="requirement.responsibility"
          :show-word-limit="true"></el-input>
      </el-form-item>
    </el-form>
    <div class="btnDiv">
      <Buttons :buttons="buttons" @cancel="cancel" @save="save" @send="send"></Buttons>
    </div>
    <MaskCover v-show="sending" title="提交中，请稍等..."></MaskCover>
  </div>
</template>

<script>
import MaskCover from "@/components/maskCover";

import requirementEditRules from '@/formRules/help/requirementEditRules.js'
import { getRegionTree, getRequirement, sendAdd, sendEdit } from "@/common/api/company.js";

export default {
  name: "companyMyRecruit",
  components: {
    MaskCover,
  },
  mixins: [requirementEditRules],
  computed:{
    buttons(){
      let btns = [
        {text:"取消",type:"normal",size:"l",method:"cancel"},
        {text:"保存",type:this.isRequirementPass() ? 'success' : 'normal',size:"l",method:"save"}
      ]
      if(!this.isRequirementPass()){
        btns.push({text:"发布",type:'success' ,size:"l",method:"save"})
      }
      return btns;
    }
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      sending: false,
      isEdit: false,
      startDateDisabled: {},
      endDateDisabled: {},
      // crumbs: [
      //   {label: "企业空间",value: "company",},
      //   {label: "人才服务",value: "",},
      //   {label: "我的招聘",value: "companyMyRecruit",},
      //   {label: "招聘需求申请",value: "companyRequirementEdit",choose: true,},
      // ],
      postSalaryOptions: [], //岗位薪资选项
      experienceOptions: [], //经验要求选项
      workerEducationOptions: [], //学历选项
      workerTypeOptions: [], //工作类型选项

      regionTree: [], //地理信息树
      province: {}, //省份
      cityOptions: [],
      city: {}, //城市
      districtOptions: [],
      district: {}, //区县
      address: "",
      straightCityIds: [110000, 120000, 310000, 500000, 810000, 820000], //直辖市id
      loading: false
    };
  },
  methods: {
    /**
     * 返回上一页
     */
    goBack: function () {
      let ns = this;
      ns.$router.go(-1);
    },
    /**
     * 选择省份
     */
    selectProvince(e) {
      let ns = this;
      ns.cityOptions = e.children;
      ns.city = {};
      ns.districtOptions = [];
      ns.district = {};
    },
    /**
     * 选择城市
     */
    selectCity(e) {
      let ns = this;
      ns.districtOptions = e.children;
      ns.district = {};
    },

    isRequirementPass() {
      let ns = this;
      return ns.requirement.status != 1 && this.isEdit;
    },
    /**
     * 判断当前选择省份是否直辖市
     * @param province 要判断的省份对象
     */
    isStraightCity(province) {
      let ns = this;
      return ns.straightCityIds.indexOf(province.id) != -1;
    },
    /**
     * 格式化显示状态
     * @param status 要格式化的状态
     */
    formantStatus(status) {
      let ns = this;
      if (status == null || status == undefined) {
        return {
          label: "",
        };
      }
      for (let i = 0; i < ns.statusList.length; i++) {
        if (status == ns.statusList[i].value) {
          return ns.statusList[i];
        }
      }
      return {
        label: "",
      };
    },
    /**
     * 获取选项内容
     * @return {Promise<void>}
     */
    async getOptions() {
      this.loading = true
      let ns = this;

      let api = `post_salary,experience,worker_type,worker_education`;
      // 调用公共方法中的查询字典表
      this.getDictList(ns, api).then((res) => {
        ns.postSalaryOptions = res.post_salary;
        ns.experienceOptions = res.experience;
        ns.workerEducationOptions = res.worker_education;
        ns.workerTypeOptions = res.worker_type;
        setTimeout(() => {
          this.loading = false
        }, 1000);
      });
    },
    /**
     * 获取地理信息树
     * @return {Promise<void>}
     */
    async getRegionTree() {
      let ns = this;
      let { data } = await getRegionTree();
      ns.regionTree = data;
      if (ns.isEdit) {
        ns.getRequirement();
      }
    },
    /**
     * 获取用工需求信息
     */
    async getRequirement() {
      let ns = this;
      let { code, msg, data } = await getRequirement(ns.$route.query.id);
      if (code == 200) {
        ns.requirement = data;
        //获取填入对应地址至地址框
        this.address =  ns.requirement.address
      } else {
        this.$confirm(res.msg, {
          showCancelButton: false,
          confirmButtonText: "返回",
        }).then((_) => {
          ns.$router.go(-1);
        });
      }
    },
    /**
     * 检查帮扶需求申请填写是否规范
     */
    checkRequirement() {
      return this.$refs["form"].validate()
      // let ns = this;
      // if (isEmptyStr(ns.requirement.name)) {
      //   return "请填写劳务帮扶名称";
      // }
      // if (isEmptyStr(ns.requirement.reason)) {
      //   return "请填写劳务帮扶申请原因";
      // }
      // if (isEmptyStr(ns.requirement.reason)) {
      //   return "请填写劳务帮扶申请原因";
      // }
      // if (isEmptyStr(ns.requirement.beginDate)) {
      //   return "请选择劳务帮扶期限开始日期";
      // }
      // if (isEmptyStr(ns.requirement.endDate)) {
      //   return "请选择劳务帮扶期限结束日期";
      // }
      // if (
      //   new Date(ns.requirement.beginDate) > new Date(ns.requirement.endDate)
      // ) {
      //   return "劳务帮扶期限开始日期不得晚于结束日期";
      // }
      // if (isEmptyStr(ns.requirement.post)) {
      //   return "请填写招聘岗位";
      // }
      // if (isEmptyStr(ns.requirement.salary)) {
      //   return "请选择岗位薪资";
      // }
      // if (ns.requirement.amount == 0) {
      //   return "招聘人数不能为0";
      // }
      // if (ns.requirement.experience == 0) {
      //   return "请选择经验要求";
      // }
      // if (isEmptyStr(ns.requirement.education)) {
      //   return "请选择学历";
      // }
      // if (isEmptyStr(ns.province.label)) {
      //   return "请选择省份";
      // }
      // if (isEmptyStr(ns.city.label)) {
      //   return "请选择城市";
      // }
      // if (isEmptyStr(ns.district.label) && !ns.isStraightCity(ns.province)) {
      //   return "请选择区县";
      // }
      // if (isEmptyStr(ns.address)) {
      //   return "请填写详细地址";
      // }
      // if (isEmptyStr(ns.requirement.responsibility)) {
      //   return "请填写岗位职责";
      // }
      // if (isEmptyStr(ns.requirement.requirement)) {
      //   return "请填写岗位要求";
      // }
      // return "";
    },
    /**
     * 提交申请
     * @return {Promise<void>}
     */
    send() {
      let ns = this;
      let str = ns.checkRequirement();
      console.log('str', str)
      str.then( res => {
        ns.requirement.address = ns.address
        // ns.requirement.address =
        // ns.province.label +
        // "/" +
        // ns.city.label +
        // (ns.isStraightCity(ns.province) ? "" : "/" + ns.district.label) +
        // "/" +
        // ns.address;
        ns.$confirm(
          "您确定发布这条招聘需求？"
        ).then(async (_) => {
          ns.requirement.flag = 1;
          ns.sending = true;
          // let api = ns.isEdit
          //   ? config.api.mineCompanyhelpRequirementEdit
          //   : config.api.mineCompanyhelpRequirementAdd;
          let res = null
          if(ns.isEdit){
            res = await sendEdit(ns.requirement)
          } else {
            res = await sendAdd(ns.requirement)
          }
          ns.sending = false;
          if (res.code == 200) {
            ns.$message.success("发布成功");
            ns.$router.push({
              path: "companyMyRecruit",
            });
          } else {
            ns.$message.error(res.msg);
          }
        });
      }).catch( err => {
        console.log(err)
      })
    },
    /**
     * 提交保存
     * @return {Promise<void>}
     */
    save() {
      let ns = this;
      let str = ns.checkRequirement();
      str.then( res => {
        ns.requirement.address = ns.address
        // ns.requirement.address =
        // ns.province.label +
        // "/" +
        // ns.city.label +
        // (ns.isStraightCity(ns.province) ? "" : "/" + ns.district.label) +
        // "/" +
        // ns.address;
        ns.$confirm("您确定做此次操作，保存本次数据？").then(async (_) => {
          ns.requirement.flag = 2;
          ns.sending = true;
          let res = null
          if(ns.isEdit){
            res = await sendEdit(ns.requirement)
          } else {
            res = await sendAdd(ns.requirement)
          }
          ns.sending = false;
          if (res.code == 200) {
            ns.$message.success("保存成功");
            ns.$router.push({
              path: "companyMyRecruit",
            });
          } else {
            ns.$message.error(res.msg);
          }
        });
      }).catch( err => {
        console.log(err)
      })
    },
    cancel() {
      let ns = this;
      ns.$confirm("你是否需要放弃本次操作，取消将无法保存数据？").then((_) => {
        ns.goBack();
      });
    },
  },
  mounted() {
    let ns = this;
    if (ns.$route.query.id != undefined) {
      ns.isEdit = true;
      // console.log('123',this.crumbs[3])
      // this.crumbs[3].label = '招聘需求编辑'
    }
    ns.getOptions();
    ns.getRegionTree();
    ns.startDateDisabled.disabledDate = function (time) {
      return time.getTime() + 24 * 3600 * 1000 <= Date.now();
    };
    ns.endDateDisabled.disabledDate = function (time) {
      return time.getTime() + 24 * 3600 * 1000 <= Date.now();
    };
  },
};
</script>

<style scoped>
.title{
  margin-bottom: 5px;
}
.breadcrumb {
  width: 1000px;
  margin: 20px 0;
}

.roomDiv {
  display: flex;
  justify-content: center;
  margin-bottom: 50px;
}

.roomDiv .leftDiv {
  width: 200px;
  text-align: left;
}

.roomDiv .rightDiv {
  width: 800px;
  margin-left: 30px;
}

.titleDiv {
  border-bottom: 2px solid #045db9;
  text-align: left;
  padding: 5px 0;
  font-size: 20px;
  font-weight: bold;
  color: #045db9;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.titleDiv .sendBtn {
  font-weight: normal;
  color: #ffffff;
  background: #045db9;
  border-radius: 5px;
  font-size: 15px;
  display: flex;
  align-items: center;
  padding: 10px;
}

.titleDiv .sendBtn:hover {
  cursor: pointer;
}

.msgDiv {
  margin: 40px 0;
}

::v-deep .formDiv .el-input-number .el-input__inner {
  text-align: left;
}

::v-deep .formDiv .el-textarea__inner {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
}

.btnDiv {
  display: flex;
  justify-content: left;
  margin-left: 200px;
}



.layout {
  min-height: 100vh;
  position: relative;
  padding-bottom: 150px;
  box-sizing: border-box;
}

.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
}
</style>
